package com.sch.wanandroid.ui.search

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.sch.wanandroid.constants.Constants
import com.sch.wanandroid.entity.ArticleBean
import com.sch.wanandroid.network.NetWorkManager
import com.tencent.mmkv.MMKV
import kotlinx.coroutines.launch

/**
 * Created by Sch.
 * Date: 2020/12/15
 * description:
 */
class SearchViewModel : ViewModel() {
    val recordList = MutableLiveData<ArrayList<String>>().apply {
        value = ArrayList()
    }

    init {
        val recodrdStr = MMKV.defaultMMKV().decodeString(Constants.SEARCH_RECORD)
        if (!recodrdStr.isNullOrEmpty()) {
            recordList.value!!.addAll(recodrdStr.split("|"))
        }
    }

    private val _article = MutableLiveData<List<ArticleBean>>()
    val articleLiveData: LiveData<List<ArticleBean>> = _article

    private val _errorMsg = MutableLiveData<String?>()
    val errorMsg: LiveData<String?> = _errorMsg

    private val _collectSuccess = MutableLiveData<Boolean>()
    val collectSuccess: LiveData<Boolean> = _collectSuccess

    private val _uncollectSuccess = MutableLiveData<Boolean>()
    val uncollectSuccess: LiveData<Boolean> = _uncollectSuccess

    fun getSearchData(k: String, pageNum: Int) {
        viewModelScope.launch {
            try {
                val result = NetWorkManager.apiService.query(pageNum, k)
                if (result.errorCode == 0) {
                    _article.value = result.data.datas
                } else {
                    _errorMsg.value = result.errorMsg
                }
            } catch (e: Exception) {
                _errorMsg.value = e.toString()
            }
        }
    }

    fun collect(id: Int) {
        viewModelScope.launch {
            try {
                val result = NetWorkManager.apiService.collect(id)
                if (result.errorCode == 0) {
                    _collectSuccess.value = true
                } else {
                    _collectSuccess.value = false
                    _errorMsg.value = result.errorMsg
                }
            } catch (e: Exception) {
                _errorMsg.value = e.toString()
            }
        }
    }

    fun unCollect(id: Int) {
        viewModelScope.launch {
            try {
                val result = NetWorkManager.apiService.unCollect(id)
                if (result.errorCode == 0) {
                    _uncollectSuccess.value = true
                } else {
                    _collectSuccess.value = false
                    _errorMsg.value = result.errorMsg
                }
            } catch (e: Exception) {
                _errorMsg.value = e.toString()
            }
        }
    }

    fun saveSearchRecord(recordList: ArrayList<String>) {
        MMKV.defaultMMKV().encode(Constants.SEARCH_RECORD, recordList.joinToString("|"))
    }
}